package net.dgi.common.match.impl;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Viva IntelliJ IDEA.
 * User: Deian Date: Sep 30, 2010 Time: 9:41:39 PM
 */
public class FunctionRegistryImpl implements FunctionRegistry {
    private Map<Class, List<Function>> cache = new HashMap<Class, List<Function>>();
    private static final Set<String> METHODS_TO_IGNORE = new HashSet<String>();
    static {
        for(Method m : Object.class.getDeclaredMethods()) {
            METHODS_TO_IGNORE.add(m.getName());
        }
    }

    public List<Function> get(Class match) {
        return cache.get(match);
    }

    public synchronized void register(Object o) {
        if (o == null) { return; }
        Class fClass = o.getClass();

        for(Method m : fClass.getDeclaredMethods()) {
            String name = m.getName();
            if (METHODS_TO_IGNORE.contains(name)) { continue; }
            if (m.getParameterTypes().length == 0) { continue; }

            Function function = new Function(o, m);
            for(Class classAsKey : m.getParameterTypes()) {
                List<Function> list = cache.get(classAsKey);
                if (list == null) {
                    list = new ArrayList<Function>();
                }
                list.add(function);
                cache.put(classAsKey, list);
            }
        }

    }
}
